package com.jt.interceptor;

import com.jt.pojo.User;
import com.jt.util.ObjectMapperUtil;
import com.jt.util.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Li Yu
 * @Date: 2020/11/20 14:02
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JedisCluster jedisCluster;
    /**
     * 参数介绍
     * @param request   用户请求对象
     * @param response  服务器响应对象
     * @param handler   当前处理器本身
     * @return  Boolean true 请求放行 false请求拦截     一般配合重定向使用
     *          如果没登录，重定向到登录页面
     * @throws Exception
     *
     *  需求：如何判断用户是否登录
     *  依据： 1.Cookie    2.判断redis
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断cookie中是否有记录
        String ticket=null;
        Cookie[] cookies=request.getCookies();
        if (cookies!=null&&cookies.length>0) {
            for (Cookie cookie : cookies) {
                if ("JT_TICKET".equals(cookie.getName())){
                    ticket=cookie.getValue();
                    break;
                }
            }
        }
        //判断cookie数据是否有效
        if (!StringUtils.isEmpty(ticket)){
            if (jedisCluster.exists(ticket)){ //表示用户已登录
                String userJSON=jedisCluster.get(ticket);
                //利用request对象进行数据的传递 先存再取
                User user= ObjectMapperUtil.toObject(userJSON, User.class);
                request.setAttribute("JT_USER",user);
                UserThreadLocal.set(user);
                //放行
                return true;
            }
        }
        //重定向到登录页面
        response.sendRedirect("/user/login.html");

        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        request.removeAttribute("JT_USER");
        UserThreadLocal.remove();
    }
}
